package hivi.vn.hivigold.database;

import hivi.vn.hivigold.fragment.ReportFragment;
import hivi.vn.hivigold.objects.Employee;
import hivi.vn.hivigold.objects.Gold;
import hivi.vn.hivigold.objects.HistoryDetail;
import hivi.vn.hivigold.objects.HistoryMaster;
import hivi.vn.hivigold.objects.Item;
import hivi.vn.hivigold.objects.Partner;
import hivi.vn.hivigold.objects.Report;
import hivi.vn.hivigold.objects.ReportFilter;
import hivi.vn.hivigold.objects.Stock;
import hivi.vn.hivigold.objects.VoucherDetail;
import hivi.vn.hivigold.objects.VoucherMaster;
import hivi.vn.hivigold.utils.Formats;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.graphics.Paint.Join;
import android.os.StrictMode;
import android.util.Log;

public class WebService {
	private static final String LOGIN = "Login";
	private static final String TEST = "Test";
	private static final String GETITEMBYID = "GetItemByID";
	private static final String GETGOLDPRICE = "getGoldPrice";
	private static final String UPDATEGOLDPRICE = "updateGoldPrice";
	private static final String GETPARTNER = "getPartner";
	private static final String UPDATEPARTNER = "updatePartner";
	private static final String DELETEPARTNER = "deletePartner";
	private static final String NEWVOUCHER = "newVoucher";
	private static final String NEWPARTNER = "insertPartner";
	private static final String REPORTNXT = "reportNXT";
	private static final String REPORTNM = "reportNM";
	private static final String REPORTDT = "reportHBDT";
	private static final String CHECKPARTNERID = "checkPartnerID";
	private static final String GETEMPLOYEE = "getEmployee";
	private static final String GETSTOCK = "getStock";
	private static final String CALPRICE = "calPrice";
	private static final String PRINTVOUCHER = "Print";
	private static final String PRINTVOUCHER2 = "PrintVoucher";
	private static final String PRINTDIAMOND = "PrintDiamond";
	private static final String DELETEVOUCHER = "deleteVoucher";
	private static final String HISTORYMASTER = "getHistoryMaster";
	private static final String HISTORYDETAIL = "getHistoryDetail";
	private static final String CHECKVOUCHER = "checkVoucher";
	private static final String GETGIAAU = "getGiaAU";
	private static final String CHECKTONKHO = "checkTonKho";

	public static String checkVoucher(Context c, String stt_rec) {
		String result = callWebServiceMethod(c, CHECKVOUCHER, new String[] { "stt_rec" }, new String[] { stt_rec });
		return result;
	}

	public static ArrayList<ArrayList<HistoryDetail>> getHistoryDetail(Context c, ArrayList<HistoryMaster> arrMaster) {
		ArrayList<ArrayList<HistoryDetail>> arrDetail = new ArrayList<ArrayList<HistoryDetail>>();

		for (int i = 0; i < arrMaster.size(); i++) {
			ArrayList<HistoryDetail> arr = new ArrayList<HistoryDetail>();
			String result = callWebServiceMethod(c, HISTORYDETAIL, new String[] { "stt_rec" }, new String[] { arrMaster.get(i).getStt_rec() });
			try {
				JSONArray jsons = new JSONArray(result);
				for (int j = 0; j < jsons.length(); j++) {
					JSONObject json = jsons.getJSONObject(j);
					HistoryDetail detail = new HistoryDetail(json);
					arr.add(detail);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			arrDetail.add(arr);
		}

		return arrDetail;
	}

	public static ArrayList<HistoryMaster> getHistoryMaster(Context c, ReportFilter filter) {
		String result = callWebServiceMethod(c, HISTORYMASTER, new String[] { "dFrom", "dTo", "partner", "employee", "stock", "group", "item" }, new String[] { Formats.DateFormatInsert(filter.getDfrom()), Formats.DateFormatInsert(filter.getDto()), filter.getPartner(), filter.getEmployee(), filter.getStock(), filter.getGroup(), filter.getItem() });
		ArrayList<HistoryMaster> arr = new ArrayList<HistoryMaster>();
		try {
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				JSONObject json = jsons.getJSONObject(i);
				HistoryMaster master = new HistoryMaster(json);
				arr.add(master);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static Boolean deleteVoucher(Context c, String stt_rec, String so_ct) {
		if (callWebServiceMethod(c, DELETEVOUCHER, new String[] { "stt_rec", "so_ct" }, new String[] { stt_rec, so_ct }).equals("1")) {
			return true;
		}
		return false;
	}

	public static Boolean printVoucher(Context c, String stt_rec, int type) {
		String printtype = Preferences.getPreferenceValue(c, Preferences.PRINTTYPE);
		if (printtype.equals("*")) {
			printtype = "0";
		}
		if (callWebServiceMethod(c, type == 1 ? PRINTVOUCHER : type == 2 ? PRINTDIAMOND : PRINTVOUCHER2, new String[] { "stt_rec", "user", "printtype" }, new String[] { stt_rec, Preferences.getPreferenceValue(c, Preferences.CURRENTUSER), printtype }).equals("1")) {
			return true;
		}
		return false;
	}

	public static VoucherMaster saveVoucher(Context c, VoucherMaster m, ArrayList<VoucherDetail> d) {
		m.setFK_NxID(Preferences.getPreferenceValue(c, Preferences.SALETYPE));
		m.setFK_NxID1(Preferences.getPreferenceValue(c, Preferences.BUYTYPE));
		m.setFK_TkID(Preferences.getPreferenceValue(c, Preferences.SALEACCOUNT));
		m.setFK_TkID1(Preferences.getPreferenceValue(c, Preferences.BUYACCOUNT));
		m.setFK_TkckID(Preferences.getPreferenceValue(c, Preferences.CKACCOUNT));
		String jsonDetail = "";
		for (VoucherDetail voucherDetail : d) {
			voucherDetail.setUser_id0(Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			voucherDetail.setUser_id2(Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			voucherDetail.setFK_KhoID(m.getFK_khoID());
			jsonDetail = jsonDetail + voucherDetail.toString() + ",";
		}
		jsonDetail = jsonDetail.substring(0, jsonDetail.length() - 1);
		jsonDetail = "[" + jsonDetail + "]";
		String result = callWebServiceMethod(c, NEWVOUCHER, new String[] { "master", "detail" }, new String[] { "[" + m.toString() + "]", jsonDetail });
		if (result.equals("*")) {
			return null;
		} else {
			try {
				JSONObject jsonMaster = new JSONArray(result).getJSONObject(0);
				m.setStt_rec(jsonMaster.getString("Stt_rec"));
				m.setSo_ct(jsonMaster.getString("So_ct"));
				return m;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Double calPrice(Context c, Item item, String muaban) {
		return Double.valueOf(callWebServiceMethod(c, CALPRICE, new String[] { "item", "muaban" }, new String[] { "[" + item.toString() + "]", muaban }));
	}

	public static ArrayList<Report> getReport(Context c, ReportFilter filter) {

		ArrayList<Report> arr = new ArrayList<Report>();
		String result = "";
		if (filter.getREPORTID() == ReportFragment.REPORT_BAN) {
			result = callWebServiceMethod(c, REPORTDT, new String[] { "dFrom", "dTo", "item", "group", "stock", "employee", "partner" }, new String[] { Formats.DateFormatInsert(filter.getDfrom()), Formats.DateFormatInsert(filter.getDto()), filter.getItem(), filter.getGroup(), filter.getStock(), filter.getEmployee(), filter.getPartner() });
		} else if (filter.getREPORTID() == ReportFragment.REPORT_MUA) {
			result = callWebServiceMethod(c, REPORTNM, new String[] { "dFrom", "dTo", "item", "group", "stock", "employee", "partner" }, new String[] { Formats.DateFormatInsert(filter.getDfrom()), Formats.DateFormatInsert(filter.getDto()), filter.getItem(), filter.getGroup(), filter.getStock(), filter.getEmployee(), filter.getPartner() });
		} else if (filter.getREPORTID() == ReportFragment.REPORT_NXT) {

			result = callWebServiceMethod(c, REPORTNXT, new String[] { "dFrom", "dTo", "item", "group", "groupme", "stock", "ps", "tk" }, new String[] { Formats.DateFormatInsert(filter.getDfrom()), Formats.DateFormatInsert(filter.getDto()), filter.getItem(), filter.getGroup(), "", filter.getStock(), "0", "1" });

		}
		try {
			Report total = new Report();
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				Report p = new Report(filter.getREPORTID(), jsons.getJSONObject(i));
				arr.add(p);
				switch (filter.getREPORTID()) {
				case ReportFragment.REPORT_BAN:
					total.setSl_ban(total.getSl_ban() == null ? p.getSl_ban() : total.getSl_ban() + p.getSl_ban());
					total.setTien_ban(total.getTien_ban() == null ? p.getTien_ban() : total.getTien_ban() + p.getTien_ban());
					total.setTien_von(total.getTien_von() == null ? p.getTien_von() : total.getTien_von() + p.getTien_von());
					total.setLai(total.getLai() == null ? p.getLai() : total.getLai() + p.getLai());
					break;
				case ReportFragment.REPORT_MUA:
					total.setSl_mua(total.getSl_mua() == null ? p.getSl_mua() : total.getSl_mua() + p.getSl_mua());
					total.setTien_mua(total.getTien_mua() == null ? p.getTien_mua() : total.getTien_mua() + p.getTien_mua());
					break;
				case ReportFragment.REPORT_NXT:
					total.setSl_td(total.getSl_td() == null ? p.getSl_td() : total.getSl_td() + p.getSl_td());
					total.setSl_tc(total.getSl_tc() == null ? p.getSl_tc() : total.getSl_tc() + p.getSl_tc());
					total.setSl_nhap(total.getSl_nhap() == null ? p.getSl_nhap() : total.getSl_nhap() + p.getSl_nhap());
					total.setSl_xuat(total.getSl_xuat() == null ? p.getSl_xuat() : total.getSl_xuat() + p.getSl_xuat());
					total.setAu_td(total.getAu_td() == null ? p.getAu_td() : total.getAu_td() + p.getAu_td());
					total.setAu_tc(total.getAu_tc() == null ? p.getAu_tc() : total.getAu_tc() + p.getAu_tc());
					total.setAu_nhap(total.getAu_nhap() == null ? p.getAu_nhap() : total.getAu_nhap() + p.getAu_nhap());
					total.setAu_xuat(total.getAu_xuat() == null ? p.getAu_xuat() : total.getAu_xuat() + p.getAu_xuat());
					total.setDu_dau(total.getDu_dau() == null ? p.getDu_dau() : total.getDu_dau() + p.getDu_dau());
					total.setDu_cuoi(total.getDu_cuoi() == null ? p.getDu_cuoi() : total.getDu_cuoi() + p.getDu_cuoi());
					total.setTien_nhap(total.getTien_nhap() == null ? p.getTien_nhap() : total.getTien_nhap() + p.getTien_nhap());
					total.setTien_xuat(total.getTien_xuat() == null ? p.getTien_xuat() : total.getTien_xuat() + p.getTien_xuat());
					break;
				}
			}
			if (arr.size() != 0) {
				arr.add(total);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static boolean deletePartner(Context c, String id) {
		String result = callWebServiceMethod(c, DELETEPARTNER, new String[] { "id" }, new String[] { id });
		if (result.equals("1")) {
			return true;
		}
		return false;
	}

	public static boolean checkPartnerID(Context c, String id) {
		String result = callWebServiceMethod(c, CHECKPARTNERID, new String[] { "id" }, new String[] { id });
		if (result.equals("1")) {
			return true;
		}
		return false;
	}

	public static boolean insertPartner(Context c, Partner p) {
		JSONObject json = new JSONObject();
		try {
			json.put("DoitacID", p.getPartnerID());
			json.put("DoitacName", p.getPartnerName());
			json.put("DoitacAdd", p.getPartnerAddress());
			json.put("DoitacTel", p.getPartnerTel());
			json.put("DoitacFax", p.getPartnerFax());
			json.put("DoitacEmail", p.getPartnerMail());
			json.put("DienGiai", p.getPartnerNote());
			json.put("Imagepath", p.getPartnerImage());
			json.put("User_id0", Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			json.put("User_id2", Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			if (callWebServiceMethod(c, NEWPARTNER, new String[] { "partner" }, new String[] { "[" + json.toString() + "]" }).equals("1")) {
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static boolean updatePartner(Context c, Partner p) {

		JSONObject json = new JSONObject();
		try {
			json.put("DoitacID", p.getPartnerID());
			json.put("DoitacName", p.getPartnerName());
			json.put("DoitacAdd", p.getPartnerAddress());
			json.put("DoitacTel", p.getPartnerTel());
			json.put("DoitacFax", p.getPartnerFax());
			json.put("DoitacEmail", p.getPartnerMail());
			json.put("DienGiai", p.getPartnerNote());
			json.put("Imagepath", p.getPartnerImage());
			json.put("User_id2", Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			if (callWebServiceMethod(c, UPDATEPARTNER, new String[] { "partner" }, new String[] { "[" + json.toString() + "]" }).equals("1")) {
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static ArrayList<Partner> getPartners(Context c, String condition) {
		ArrayList<Partner> arr = new ArrayList<Partner>();
		String result = callWebServiceMethod(c, GETPARTNER, new String[] { "condition" }, new String[] { condition });
		try {
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				Partner p = new Partner(jsons.getJSONObject(i));
				if (p != null) {
					arr.add(p);
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static ArrayList<Stock> getStock(Context c) {
		ArrayList<Stock> arr = new ArrayList<Stock>();
		String result = callWebServiceMethod(c, GETSTOCK, new String[] {}, new String[] {});
		try {
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				Stock p = new Stock(jsons.getJSONObject(i));
				arr.add(p);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static ArrayList<Employee> getEmployee(Context c) {
		ArrayList<Employee> arr = new ArrayList<Employee>();
		String result = callWebServiceMethod(c, GETEMPLOYEE, new String[] {}, new String[] {});
		try {
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				Employee p = new Employee(jsons.getJSONObject(i));
				arr.add(p);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static boolean updateGoldPrice(Context c, Gold g) {

		JSONObject json = new JSONObject();
		try {
			json.put("tienteID", g.getTienteID());
			json.put("Gia_mua", g.getMua_vao());
			json.put("Gia_ban", g.getBan_ra());
			json.put("User_id2", Preferences.getPreferenceValue(c, Preferences.CURRENTUSER));
			if (callWebServiceMethod(c, UPDATEGOLDPRICE, new String[] { "goldprice" }, new String[] { "[" + json.toString() + "]" }).equals("1")) {
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static ArrayList<Gold> getGoldPrice(Context c) {
		ArrayList<Gold> arr = new ArrayList<Gold>();
		String result = callWebServiceMethod(c, GETGOLDPRICE, new String[] {}, new String[] {});
		try {
			JSONArray jsons = new JSONArray(result);
			for (int i = 0; i < jsons.length(); i++) {
				Gold g = new Gold(jsons.getJSONObject(i));
				arr.add(g);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return arr;
	}

	public static Item getItemByID(Context c, String id, String muaban) {
		Item i = null;
		String result = callWebServiceMethod(c, GETITEMBYID, new String[] { "id", "muaban" }, new String[] { id, muaban });
		if (!result.equals("0")) {
			try {
				JSONArray json = new JSONArray(result);
				i = new Item(json.getJSONObject(0));
				return i;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Item getGiaAU(Context c, String id, String muaban) {
		Item i = null;
		String result = callWebServiceMethod(c, GETGIAAU, new String[] { "id", "muaban" }, new String[] { id, muaban });
		if (!result.equals("0")) {
			try {
				JSONArray json = new JSONArray(result);
				i = new Item(json.getJSONObject(0));
				return i;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static Integer checkTonKho(Context c, String id) {
		Integer i = 0;
		String result = callWebServiceMethod(c, CHECKTONKHO, new String[] { "id" }, new String[] { id });
		if (!result.equals("0")) {
			try {
				JSONArray json = new JSONArray(result);
				if (json.length() > 0) {
					i = json.getJSONObject(0).getInt("So_luong");
					return i;
				} else
					return 0;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static boolean checkLogin(Context c, String username, String password) {
		String result = callWebServiceMethod(c, LOGIN, new String[] { "username", "password" }, new String[] { username, password });
		if (result.equals("*")) {
			return false;
		}
		try {
			JSONArray json = new JSONArray(result);
			JSONObject obj = json.getJSONObject(0);
			Preferences.editPreferenceValue(c, Preferences.EMPLOYEEID, obj.getString("m_bpkdid_hdt"));
			Preferences.editPreferenceValue(c, Preferences.EMPLOYEENAME, obj.getString("BpkdName"));
			Preferences.editPreferenceValue(c, Preferences.STOCKID, obj.getString("m_khoid_hdt"));
			Preferences.editPreferenceValue(c, Preferences.STOCKNAME, obj.getString("KhoName"));
			Preferences.editPreferenceValue(c, Preferences.PARTNERID, obj.getString("m_doitacid_hdt"));
			Preferences.editPreferenceValue(c, Preferences.PARTNERNAME, obj.getString("DoiTacName"));
			Preferences.editPreferenceValue(c, Preferences.CURRENTUSER, obj.getString("UserID"));
			Preferences.editPreferenceValue(c, Preferences.ACCESS, obj.getString("Access").toLowerCase().equals("null") ? null : obj.getString("Access"));
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public static boolean Test(Context c) {
		String result = callWebServiceMethod(c, TEST, new String[] {}, new String[] {});
		return result.equals("*") ? false : true;
	}

	static String callWebServiceMethod(Context c, String methodname, String[] keys, String[] values) {
		String URL = Preferences.getPreferenceValue(c, Preferences.URL);
		String NAMESPACE = Preferences.getPreferenceValue(c, Preferences.NAMESPACE);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		SoapObject request = new SoapObject(NAMESPACE, methodname);
		for (int i = 0; i < keys.length; i++) {
			request.addProperty(keys[i], values[i]);
		}
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = true;
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		try {

			androidHttpTransport.call(NAMESPACE + methodname, envelope);
			String result = "*";
			if (envelope.bodyIn instanceof SoapFault) {
				result = ((SoapFault) envelope.bodyIn).faultstring;
			} else {
				result = ((SoapObject) envelope.bodyIn).getPropertyAsString(0);
			}
			return String.valueOf(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.i("SERVICE", e.toString());
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			Log.i("SERVICE", e.toString());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("SERVICE", e.toString());
		}
		return "*";
	}

}
